package com.siruier.boss.ui.activity.login

import android.content.Intent
import android.view.View
import com.siruier.boss.api.core.MD5Util
import com.siruier.boss.api.core.launchUI
import com.siruier.boss.api.core.toData
import com.siruier.boss.api.loginApi
import com.siruier.boss.databinding.ActivityRegisterBinding
import com.siruier.boss.ui.api.ApiObserver
import com.siruier.boss.ui.base.BaseActivity
import com.siruier.boss.ui.ext.toastMessageLong
import com.siruier.boss.ui.ext.value
import com.siruier.boss.ui.utils.variableView

class RegisterActivity : BaseActivity<ActivityRegisterBinding>() {

    override fun initView() {
        bindViewClick(vb.tbVcode, vb.buttonRegister)
        variableView {
            addTextView(vb.etPhone)
            addTextView(vb.etPasswrod)
            addTextView(vb.etVcode)
            addOnValidationResultListener(vb.buttonRegister)
            addOnValidationInterceptListener(::validator)
        }
    }

    override fun onClick(v: View?) {
        when (v) {
            vb.tbVcode -> {
                launchUI({ loginApi.smsSend(vb.etPhone.value, "reg").toData() }, ApiObserver(this) {
                    vb.tbVcode.start()
                })
            }
            vb.buttonRegister -> {
                launchUI({
                    loginApi.register(
                        vb.etPhone.value,
                        MD5Util.md5(vb.etPasswrod.value),
                        vb.etVcode.value,
                        vb.etInvitePhone.value
                    ).toData()
                }, ApiObserver(this) {
                    "注册成功".toastMessageLong()
                    setResult(RESULT_OK, Intent().apply {
                        putExtra("phone", vb.etPhone.value)
                        putExtra("passwrod", vb.etPasswrod.value)
                    })
                    finish()
                })
            }
        }
    }

    private fun validator(view: View) = when (view) {
        vb.etPhone -> vb.tbVcode.enable(vb.etPhone.length() == 11)
        vb.etVcode -> vb.etVcode.length() == 4
        vb.etInvitePhone -> vb.etInvitePhone.length() == 11
        else -> null
    }
}